package com.hdu.webServer.write;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;


@Slf4j
public class WriteServer {

    public static void main(String[] args) throws IOException {

        Selector selector = Selector.open();

        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.bind(new InetSocketAddress("localhost", 8080));
        ssc.configureBlocking(false);
        ssc.register(selector, SelectionKey.OP_ACCEPT);

        while (true) {
            selector.select();
            Iterator<SelectionKey> readyKeys = selector.selectedKeys().iterator();
            while (readyKeys.hasNext()) {
                SelectionKey readyKey = readyKeys.next();
                readyKeys.remove();
                if (readyKey.isAcceptable()) {
                    handleAcceptable(ssc, selector);
                }
                else if (readyKey.isWritable()) {
                    handleWritable(readyKey);
                }
            }
        }
    }

    @SuppressWarnings("all")
    private static void handleWritable(SelectionKey readyKey) throws IOException {
        SocketChannel sc = (SocketChannel) readyKey.channel();
        ByteBuffer buffer = (ByteBuffer) readyKey.attachment();
        int writeLen = sc.write(buffer);
        log.info("write length : {}", writeLen);
        if (!buffer.hasRemaining()) {
            readyKey.attach(null);
            readyKey.interestOps(readyKey.interestOps() - SelectionKey.OP_WRITE);
        }
    }

    private static void handleAcceptable(ServerSocketChannel ssc, Selector selector) throws IOException {

        SocketChannel sc = ssc.accept();
        sc.configureBlocking(false);
        SelectionKey scKey = sc.register(selector, 0, null);
        scKey.interestOps(SelectionKey.OP_READ);

        ByteBuffer buffer = getByteBuffer();

        int writeLen = sc.write(buffer);
        log.info("write length : {}", writeLen);
        if (buffer.hasRemaining()) {
            // 注册可写事件 有剩余空间才写
            scKey.interestOps(scKey.interestOps() + SelectionKey.OP_WRITE);
            // 没写完的buffer挂到 scKey上面去
            scKey.attach(buffer);
        }
    }

    private static ByteBuffer getByteBuffer() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 3000000; i++) {
            sb.append("a");
        }
        return Charset.defaultCharset().encode(sb.toString());
    }
}
